package org.wanda.pv.controller.business;



import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.nutz.dao.Dao;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.model.business.Attachment;
import org.wanda.pv.model.business.Mark;
import org.wanda.pv.service.file.FileUploadService;
import org.wanda.pv.util.ExcelUtil;
import org.wanda.pv.util.WordToHtml;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excel")
@SuppressWarnings("all")
public class ExcelController {
    private Log log = Logs.getLog(this.getClass());


    @Autowired
    private Dao dao;
    @Autowired
    private FileUploadService uploadService;
    @RequestMapping("/wordDownload")
    public void wordDownload(Long attachmentId, HttpServletResponse response,HttpServletRequest request) throws Exception {
        try {
            Attachment attachment = dao.fetch(Attachment.class, attachmentId);
            File file = new File(attachment.getServerPath());
            String fileName = attachment.getName();
            String ext = attachment.getExName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(attachment.getServerPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            fileName+=ext;
            // 设置response的Header
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }


    }

    @RequestMapping("/wordToHtml")
    public Object wordToHtml(Long attachmentId) {


        Attachment attachment = dao.fetch(Attachment.class, attachmentId);

        String serverPath = attachment.getServerPath();
        String resourcesPath = uploadService.getBasePath();
        System.out.println("resourcesPath::: == :::" + resourcesPath);
        try {
            String s = WordToHtml.wordToHtml(serverPath, resourcesPath);

            return s;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "服务器内部错误!";
        }


    }


    @RequestMapping("/getTable")
    public Object getTable(){
        List<Map> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("name","销售物业施工图第三方审查问题统计汇总表");
        map.put("pos",1);
        list.add(map);

        map = new HashMap<>();
        map.put("name","持有商业施工图第三方审查问题统计汇总表");
        map.put("pos",2);
        list.add(map);

        map = new HashMap<>();
        map.put("name","施工图第三方审查问题统计明细表");
        map.put("pos",3);
        list.add(map);


        map = new HashMap<>();
        map.put("name","商业项目施工图审查要点—建筑");
        map.put("pos",4);
        list.add(map);



        return Result.success("success",list);
    }

    @RequestMapping("/tableHtml/{pos}")
    public String tableHtml(@PathVariable String pos)throws Exception{
        ExcelUtil excel = new ExcelUtil();

        InputStream resourceAsStream = ExcelController.class.getClassLoader().getResourceAsStream("table0"+pos+".xlsx");
        String xlsx = excel.excelToHtml(resourceAsStream, "xlsx");
        return xlsx;
    }



    @RequestMapping("/table/{pos}")
    public void table01(HttpServletResponse response,
                     HttpServletRequest request,
                        @PathVariable String pos) throws Exception{

        ExcelUtil excel = new ExcelUtil();

        InputStream resourceAsStream = ExcelController.class.getClassLoader().getResourceAsStream("table0"+pos+".xlsx");
        Workbook tempWorkbook = excel.getTempWorkbook(resourceAsStream);

        String fileName = tempWorkbook.getSheetAt(0).getSheetName();


        download(fileName,tempWorkbook,response,request);

    }


    public void  download(String fileName,
                          Workbook wb,
                          HttpServletResponse response,
                          HttpServletRequest request)throws Exception{
        ServletOutputStream fileOut = null;
        try{

            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            }

            response.reset();
            fileOut = response.getOutputStream();
            response.setContentType("application/x-download; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
            wb.write(fileOut);
            fileOut.flush();
            fileOut.close();
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                }
            }
        }




    }

}
